#ifndef DO_PROPERTIES_H
#define DO_PROPERTIES_H

/*
Copyright (c) 2014, ebaklund
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, 
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, 
   this list of conditions and the following disclaimer in the documentation 
   and/or other materials provided with the distribution.

3. Neither the name of the <ORGANIZATION> nor the names of its contributors 
   may be used to endorse or promote products derived from this software 
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

#include <Do/SyntacticCandy.h>

#include <functional>
#include <type_traits>
#include <exception>


namespace Do { namespace Properties
{
  class OutPropertyException;
  class InPropertyException;

  class PropertyOwnerBase;
  template <typename T> class OutProperty;
  template <typename T> class InProperty;
}}


/** 
 * Base class of property owner classes.
 * PropertyOwnerBase contains convenience functions for property owner classes.
 * Property owner classes should inherit PropertyOwnerBase as a *protected*
 * base class as the convenience function are for internal use only.
 *
 *  Example :
  \verbatim

  template<typename T>
  struct AddFunctor : protected Do::PropertyOwnerBase
    {
      struct In 
        {
          Do::InProperty<T> a;
          Do::InProperty<T> b;
        } in;

      struct Out 
        {
          Do::OutProperty<T> sum;
        } out;

      AddFunctor() 
        {
          in.a    >>= [&] () { setDirty(out.sum); };
          in.b    >>= [&] () { setDirty(out.sum); };
          out.sum >>= [&] (T& sum) { sum = in.a() + in.b(); };
        }
    };
    ...
  TEST_METHOD(TestAddFunctor)
    {
      AddFunctor<int> adder;

      adder.in.a <<= 123; 
      adder.in.b <<= 99;

      Assert::AreEqual(adder.out.sum(), 222);
    }

  \endverbatim
 */

class Do::Properties::PropertyOwnerBase 
  {
  private:

    template<typename U, typename L> static
    void connect (OutProperty<U>& out_property, L&& evaluate_callback)
      {
        out_property.connectEvaluateCallback(std::forward<L>(evaluate_callback)); 
      }

    template<typename U, typename L> static
    void connect (InProperty<U>& in_property, L&& change_callback)
      {
        in_property.connectChangeCallback(std::forward<L>(change_callback)); 
      }

  public:

    PropertyOwnerBase() = default;

    /**
     * Marks the value contained in the out_property as outdated.
     */
    template <typename U> static
    void setDirty(OutProperty<U>& out_property)
      {
        out_property.setDirty();
      }

    /**
     * Checks if the value contained in the out_property is outdated.
     */
    template <typename U> static
    bool isDirty(OutProperty<U> const& out_property)
      {
        return out_property.isDirty();
      }

    /**
     * Connects the evaluate_callback to the out_property.
     */ 
    template<typename U, typename L> friend
    void operator >>= (OutProperty<U>& out_property, L&& evaluate_callback)
      {
        connect(out_property, std::forward<L>(evaluate_callback)); 
      }

    /**
     * Assigns a value to the in_property without change notification.
     */
    template <typename U> static
    void quietlySet(InProperty<U>& in_property, U const& value)
      {
        in_property.quietlySet(value);
      }

    /**
     * Connects the change_callback to the in_property.
     */ 
    template<typename U, typename L> friend
    void operator >>= (InProperty<U>& in_property, L&& change_callback)
      {
        connect(in_property, std::forward<L>(change_callback)); 
      }

  }; // Do::PropertyOwnerBase


/**
 * Thrown by OutProperty when errors are detected.
 */

class Do::Properties::OutPropertyException : public std::exception
  {
  public:
    OutPropertyException(const char * const & msg) : std::exception(msg)
    {}
  };


/**
 * Thrown by InProperty when errors are detected.
 */

class Do::Properties::InPropertyException : public std::exception
  {
  public:
    InPropertyException(const char * const & msg) : std::exception(msg)
    {}

  };


/** 
 * Provides a lazily evaluated output value.
 * Throws OutPropertyException if the evaluation callback is not set.
 * Template type T cannot be void.
 */

template<typename T>
class Do::Properties::OutProperty
{
private:
  static_assert(!std::is_void<T>::value, "OutProperty<void> - Unsupported template argument.");

  friend class PropertyOwnerBase;

  struct InternalState
    {
      std::function<void (T&)> evaluate_callback;

      mutable bool  is_dirty;
      mutable T     cached_value;

      InternalState()
        : evaluate_callback(nullptr),
          is_dirty(true)
        {}

      T const& getValue() const 
        {
          if (! evaluate_callback)
            throw OutPropertyException("Attmpt to get value from OutProperty without evaluate callback.");

          if (testAndClear(is_dirty))
            evaluate_callback(cached_value);

          return cached_value;
        }
    } _ ;

protected:

  /**
   * Marks out-property value for needing evaluation.
   * Used by PropertyOwnerBase.
   */
  void setDirty()
    {
      _.is_dirty = true;
    }

  /**
   * Returns true if out-property value needs evaluation.
   * Used by PropertyOwnerBase.
   */
  bool isDirty() const
    {
      return _.is_dirty;
    }

  /**
   * Connects the evaluation callback
   * Used by PropertyOwnerBase.
   */
  template<typename L>
  void connectEvaluateCallback (L&& evaluate_callback)
    {
      _.evaluate_callback = std::bind(std::forward<L>(evaluate_callback), std::placeholders::_1); 
      _.is_dirty = true;
    }

public:

  OutProperty() = default;

  /**
   * Returns the lazily evaluated property value.
   * Throws an OutPropertyException if the evaluation callback is not connected.
   */
  T const& operator()() const 
    {
      return _.getValue();
    }
  
  /**
   * Assigns the property value to a lvalue.
   * Throws an OutPropertyException if the evaluation callback is not connected.
   */
  template <typename U=T> friend
  void operator <<= (U& value, OutProperty<U> const& out_property) 
    {
      value = out_property._.getValue();
    }

}; // Do::Properties::OutProperty


/** 
 * Caches input value and notifies value change via a callback.
 * Throws InPropertyException if the value changed callback is not set.
 * Template type T cannot be void.
 */

template<typename T> 
class Do::Properties::InProperty
{
private:
  static_assert(!std::is_void<T>::value, "InProperty<void> - Unsupported template argument.");

  friend class PropertyOwnerBase;

  typedef std::function<void ()> F;

  struct InternalStateBase
    {
      F change_callback;

      InternalStateBase()
        : change_callback(nullptr)
        {}
    };

  template<typename U=T>
  struct InternalState : public InternalStateBase
    {
      U value;
    };

  template<>
  struct InternalState<void> : public InternalStateBase
    {};

  InternalState<T> _ ;

protected:

  /**
   * Assigns a value to the in_property without change notification.
   * Used by PropertyOwnerBase.
   */
  void quietlySet(T const& value)
    {
      _.value = value;
    }

  /**
   * Connect change callback.
   * Used by PropertyOwnerBase.
   */
  void connectChangeCallback(std::function<void ()> const& change_callback) 
    {
      _.change_callback = change_callback;
    }

public:

  InProperty() = default;

  /**
   * Returns the input property valeue.
   */
  T const& operator()() const
    {
      return  _.value;
    }

  /**
   * Set the input property value and invokes change notification.
   * Throws InPropertyException if value change callback is not set.
   */
  void operator <<= (T const& value) 
    {
      if (_.value != value)
      {
        _.value = value;

        if (!_.change_callback)
          throw InPropertyException("Attempt to assign value to InProperty without value change callback.");

        _.change_callback();
      }
    }

  /**
   * Assigns the input property value to an lvalue.
   */
  friend
  void operator <<= (T& value, InProperty<T> const& in_property) 
    {
      value = in_property._.value;
    }

}; // Do::Properties::InProperty<T>

#endif // DO_PROPERTIES_H